import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { Badge, Card, message, Table, Row, Col, Button, Popconfirm } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import Ellipsis from '../../../components/Ellipsis';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import * as G from '../../../utils/common';
import styles from '../../../components/common/PateoTable/TableList.less';
import DetailModal from './detailModal';
import {downloadUrl, getKeyValueString, getMd5} from '@/utils/utils'
import MaskText from '@/components/MaskText';
import { filterAuth } from '@/support/common';
import { fingerprintFetch } from '@/utils/request';


const mapStateToProps = (state:any) => ({
    consumerLog: state.consumerLog,
    loading: state.loading.models["consumerLog"],
    menu: state.menu,
  }
);


/**
 * 用户日志 页
 */
class ConsumerLog extends PureComponent<any, any> {
  static contextTypes = {};

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      selectedRowKeys: [],
      detailVisible: false,
      exportLoading: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      page: 1,
      size: 10,
    };
    dispatch({
      type: 'consumerLog/postFetchPage',
      payload: { url: '/newFeedback/findPageList', ...tempParam },
    });
  }

  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
      const [start, end] = fields.handleTimeRange;
      fields['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
      fields['endTime'] = moment(end).format('YYYY-MM-DD HH:mm:ss');
      delete fields['handleTimeRange'];
      /* if (moment(fields.startTime).isBefore(moment(fields.endTime).subtract(1, 'months'))) {
        message.warning('操作时间区间为一个月！');
        return false;
      } else {
        return fields;
      } */
    }
    return fields;
  };

  handleFormReset = () => {
    this.setState({
      formValues: {},
    });
  };

  handleDelete = (list = []) => {};

  handleExport = () => {
    const { formValues } = this.state;
    const {
      consumerLog: {
        pageData: { pagination },
      },
    } = this.props;
    if (pagination.total > 10000 || pagination.total === 0) {
      message.warning('您目前搜索的结果等于0条或者大于10000条，请选择查询条件，精确查询范围！');
      return;
    }
    this.setState({ exportLoading: true });
    const str = `${window.g.url}/newFeedback/findListToExport`;
    const newOptions: any = {};
    const obj = Object.assign({}, formValues);
    let dataStr = getKeyValueString(obj);
    let md5 = getMd5(dataStr);
    newOptions.method = 'POST';
    newOptions.body = JSON.stringify(obj);
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        this.setState({
          exportLoading: false,
        });
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        this.setState({ exportLoading: false });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `用户日志列表${new Date().toLocaleDateString()}.xls`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      })
      .catch(() => {
        this.setState({
          exportLoading: false,
        });
        message.error('导出失败，请稍后再试!');
      });
  };

  saveDownloadRecord = (params: any) => {
    const { consumerLog: { pageData: { list, pagination }, }, loading, dispatch, location: { pathname = '/' }, menu: { permissions }, } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      page: pagination.current,
      size: pagination.pageSize,
    };
    dispatch({
      type: 'consumerLog/postDataWithResNoPut',
      payload: { url: '/newFeedback/saveDownloadRecord', ...params },
      callback: (res: any) => {
        dispatch({
          type: 'consumerLog/postFetchPage',
          payload: { url: '/newFeedback/findPageList', ...tempParam },
        });
      },
    });
  };

  handleDownloadLog = (record: any, type: string) => {
    let url = type === '0' ? record.appLogUri : record.tboxLogUri;
    if (url) {
      downloadUrl(url);
      let tempParams = {
        id: record.id,
        downloadType: type,
      };
      //  记录下载记录
      this.saveDownloadRecord(tempParams);
    } else {
      message.error('日志不存在！');
    }

    /* let tempForm = document.createElement('form');
    tempForm.action = url
    document.body.appendChild(tempForm); 
    //提交表单，实现下载
    tempForm.submit();
    document.body.removeChild(tempForm); */
  };

  handleDetail = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'consumerLog/getDataWithRes',
      payload: {
        url: '/newFeedback/findDownloadRecord', //  查询日志下载记录
        id: record.id,
      },
      callback: (res: any) => {
        const { statusCode, data } = res;
        if (statusCode === '0') {
          this.setState({
            detailVisible: true,
          });
          this.detailModal.setData({ ...record, downloadLogs: data });
          // this.detailModal.setData({...record})
        }
      },
    });
  };

  closeDetailModal = () => {
    this.setState({
      detailVisible: false,
    });
  };

  render() {
    const { consumerLog: { pageData: { list, pagination }, }, loading, dispatch, location: { pathname = '/' }, menu: { permissions }, } = this.props;
    // let pathname = '/logManager/consumerLog'
    const { formValues, selectedRowKeys, detailVisible } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '用户名',
        dataIndex: 'userName',
        render: (text: any) => {
          return <MaskText text={text} type={'name'} />;
        },
      },
      {
        title: '手机号码',
        dataIndex: 'phone',
        render(val: any) {
          return <MaskText text={val} type="phone" />;
        },
      },
      {
        title: '反馈时间',
        dataIndex: 'createDate',
      },
      {
        title: '车辆VIN',
        dataIndex: 'vin',
      },
      {
        title: '反馈单号',
        dataIndex: 'serialNumber',
      },
      {
        title: '反馈类型',
        dataIndex: 'feedbackType',
        render: (text: any) => (text === '0' ? '功能异常' : '优化建议'),
      },
      {
        title: '反馈内容',
        dataIndex: 'content',
        render: (text: any) => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      /* {
        title: '工单系统处理进度',
        dataIndex: '',
      }, */
      {
        title: 'APP日志下载次数',
        dataIndex: 'appLogCount',
      },
      {
        title: 'T-BOX日志下载次数',
        dataIndex: 'tboxLogCount',
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 240,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '下载APP日志',
              key: 'downloadAppLog',
              auth: 'consumerLog_doDetail',
              disabled: record.feedbackType === '1' || !record.appLogUri, //  优化建议 则 禁止点击
              onConfirm: () => this.handleDownloadLog(record, '0'),
            },
            {
              title: '下载T-BOX日志',
              key: 'downloadTBoxLog',
              auth: 'consumerLog_doDetail',
              disabled: record.feedbackType === '1' || !record.tboxLogUri, //  优化建议 则 禁止点击
              onConfirm: () => this.handleDownloadLog(record, '1'),
            },
            {
              title: '查看详情',
              key: 'detail',
              auth: 'consumerLog_doDetail',
              onConfirm: () => this.handleDetail(record),
            },
          ];
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys: any) => {
        this.setState({ selectedRowKeys });
      },
    };
    const tableProps = {
      columns,
      rowKey: (record: any) => record.id,
      dataSource: list,
      loading,
      pagination: paginationProps,
      rowSelection,
      selectedRowKeys,
      scroll: { x: 'max-content' },
    };

    const searchItems = [
      {
        title: '用户名',
        type: 'input',
        customStyle: 6,
        key: 'userName',
      },
      {
        title: '手机号',
        type: 'input',
        customStyle: 6,
        key: 'phone',
      },
      {
        title: '反馈日期',
        type: 'rangePicker',
        customStyle: 10,
        key: 'handleTimeRange',
      },
      {
        title: 'VIN',
        type: 'input',
        customStyle: 6,
        key: 'vin',
      },
      {
        title: '反馈类型',
        type: 'select',
        customStyle: 6,
        selectOptions: [
          { value: '0', label: '功能异常' },
          { value: '1', label: '优化建议' },
        ],
        key: 'feedbackType',
      },
      {
        title: '反馈单号',
        type: 'input',
        customStyle: 6,
        key: 'serialNumber',
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'consumerLog/postFetchPage', url: '/newFeedback/findPageList' }}
            extraArgs={{ page: 1, size: 10 }}
            saveFormValues={(val: any) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div>
            <Row>
              <Col span={12}>
                {/* <Popconfirm
                  title="是否确认删除所选数据？"
                  disabled={!(selectedRowKeys && selectedRowKeys.length > 0)}
                  onConfirm={() => this.handleDelete(selectedRowKeys)}
                >
                  <Button
                    style={{marginBottom: 8, marginRight: 8}}
                    size={"small"}
                    type={"primary"}
                    disabled={!(selectedRowKeys && selectedRowKeys.length > 0)}
                  >
                    批量删除日志
                  </Button>
                </Popconfirm> */}
              </Col>
              <Col span={12}>
                {filterAuth(
                  'consumerLog_export',
                  permissions,
                  this.props.location.pathname,
                ) ? (
                  <Button
                    style={{ float: 'right', marginBottom: 8, marginRight: 8 }}
                    type={'primary'}
                    onClick={() => this.handleExport()}
                  >
                    导出
                  </Button>
                ) : null}
              </Col>
            </Row>
          </div>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'consumerLog/postFetchPage',
              url: '/newFeedback/findPageList',
              extraArgs: {},
            }}
            formValues={formValues}
            currentName="page"
            pageSizeName="size"
          />
        </Card>
        <DetailModal
          onRef={(val: any) => (this.detailModal = val)}
          modalVisible={detailVisible}
          closeModal={this.closeDetailModal}
        />
      </div>
    );
  }
}

export default connect(mapStateToProps)(ConsumerLog);
